<template>
  <div class="app-container">

    <el-card style="margin-top: 20px">

      <div class="qu-content">

        <p>【{{ quData.quType | quTypeFilter }}】{{ quData.content }}</p>
        <p v-if="quData.image!=null && quData.image!=''">
          <el-image :src="quData.image" style="max-width:100%;" />
        </p>

        <div v-if="quData.quType === 1 || quData.quType===3">
          <el-radio-group v-model="answerValues[0]" @change="handleRadioChange">
            <el-radio v-for="an in quData.answerList" :key="an.id" :label="an.id">
              {{ an.abc }}.{{ an.content }}
              <div v-if="an.image!=null && an.image!=''" style="clear: both">
                <el-image :src="an.image" style="max-width:100%;" />
              </div>
            </el-radio>
          </el-radio-group>
        </div>

        <!-- 多选题 -->
        <div v-if="quData.quType === 2">
          <el-checkbox-group v-model="answerValues" @change="handleCheckboxChange">
            <el-checkbox v-for="an in quData.answerList" :key="an.id" :label="an.id">
              {{ an.abc }}.{{ an.content }}
              <div v-if="an.image!=null && an.image!=''" style="clear: both">
                <el-image :src="an.image" style="max-width:100%;" />
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <div v-if="analysisShow" style="margin-top: 20px; color: #1890ff; font-weight: bold">
          正确答案：{{ rightTags.join(' ') }}
        </div>

      </div>

    </el-card>

    <el-card v-if="analysisShow" class="qu-analysis" style="margin-top: 20px">
      错题解析：
      <div style="margin-top: 10px">
        <el-tooltip content="调用AI生成本题解析" placement="top">
          <el-button class="ai-analyze-btn" type="primary" size="mini" @click="handleAiAnalysis">
            <svg-icon icon-class="education" style="margin-right: 6px" />
            AI解析
          </el-button>
        </el-tooltip>
      </div>
    </el-card>

    <el-card v-if="analysisShow" class="qu-analysis" style="margin-top: 20px;">
      选项解析：
      <div v-for="an in quData.answerList" v-if="an.analysis" :key="an.id" class="qu-analysis-line">
        <p style="color: #555;">{{ an.content }}：</p>
        <p style="color: #1890ff;">{{ an.analysis }}</p>
      </div>
      <p v-if="analysisCount === 0">暂无选项解析</p>

    </el-card>

    <div style="padding-top: 30px">
      <el-button type="primary" @click="handNext">继续下一题</el-button>
      <el-button type="info" @click="onCancel">返回</el-button>
    </div>

    <el-dialog title="AI解析" :visible.sync="aiDialogVisible" width="580px">
      <div v-loading="aiLoading" style="min-height: 120px; white-space: pre-wrap; line-height: 22px; color: #333">
        {{ aiText }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="aiDialogVisible=false">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchDetail } from '@/api/qu/qu'
import { nextQu, fillResult } from '@/api/user/repo'
import { aiAnalysis } from '@/api/ai'

export default {
  name: 'BookTrain',
  filters: {
    quTypeFilter(quType) {
      const quTypes = { 1: '单选题', 2: '多选题', 3: '判断题' }
      return quTypes[quType] || '未知题型'
    }
  },
  data() {
    return {

      examId: '',
      quId: '',
      tags: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'],
      analysisShow: false,
      quData: {

      },
      answerValues: [],
      rightValues: [],
      rightTags: [],
      analysisCount: 0

      ,aiDialogVisible: false
      ,aiLoading: false
      ,aiText: ''
    }
  },
  created() {
    this.examId = this.$route.params.examId

    this.fetchNextQu()
  },
  methods: {

    // 清理值
    clearValues() {
      this.answerValues = []
      this.rightValues = []
      this.analysisShow = false
      this.rightTags = []
      this.analysisCount = 0
    },

    handleRadioChange(value) {
      // 单选题和判断题的处理
      this.$set(this.answerValues, 0, value)
    },

    handleCheckboxChange(value) {
      // 多选题的处理
      this.answerValues = value
    },

    // 查找试卷详情
    fetchQuDetail(id) {
      // 当前赋值
      this.quId = id
      this.clearValues()

      fetchDetail(id).then(response => {
        // 题目信息
        this.quData = response.data

        // 保存正确答案
        this.quData.answerList.forEach((an, index) => {
          an.abc = this.tags[index]

          // 用户选定的
          if (an.isRight) {
            this.rightValues.push(an.id)
            this.rightTags.push(an.abc)
          }

          // 计算有解析的答案数量
          if (an.analysis) {
            this.analysisCount++
          }
        })
      }).catch(error => {
        console.error('获取题目详情失败:', error)
        this.$message.error('获取题目详情失败，请稍后重试')
      })
    },
    async handleAiAnalysis() {
      const answers = (this.quData.answerList || []).map((an) => ({ tag: an.abc, content: an.content || '' }))
      const payload = { content: this.quData.content || '', answers }
      this.aiDialogVisible = true
      this.aiLoading = true
      this.aiText = ''
      try {
        const resp = await aiAnalysis(payload)
        if (resp && resp.code === 0) {
          this.aiText = resp.data
        } else {
          this.aiText = (resp && resp.data) || 'AI服务暂不可用'
        }
      } catch (e) {
        this.aiText = '调用失败：' + (e && e.message ? e.message : '未知错误')
      } finally {
        this.aiLoading = false
      }
    },

    fetchNextQu() {
      // 查找下一个
      nextQu(0, this.examId, 'default_user', this.quId).then(response => {
        if (response && response.code === 0 && response.data && response.data.id) {
          this.fetchQuDetail(response.data.id)
        } else {
          this.$message.info('没有更多题目了')
        }
      }).catch(error => {
        console.error('获取下一题失败:', error)
        this.$message.error('获取题目失败，请稍后重试')
      })
    },
    onCancel() {
      this.$router.push({ name: 'PublicRepo' })
    },

    handNext() {
      // 直接显示下一个
      if (this.analysisShow) {
        // 正确显示下一个
        this.fetchNextQu()
      } else {
        // 直接判断正确性
        let isCorrect = false;
        if (this.quData.quType === 1 || this.quData.quType === 3) {
          // 单选题或判断题
          isCorrect = this.rightValues.join(',') === this.answerValues[0];
        } else if (this.quData.quType === 2) {
          // 多选题
          const userAnswers = [...this.answerValues].sort();
          const correctAnswers = [...this.rightValues].sort();
          isCorrect = userAnswers.join(',') === correctAnswers.join(',');
        }
        
        if (isCorrect) {
          this.$message({
            message: '回答正确，你好棒哦！',
            type: 'success'
          })

          // 正确显示下一个
          this.fetchNextQu()
          
          // 记录正确答案
          fillResult({
            repoId: this.examId,
            sequence: this.quId,
            clear: true
          }).then(response => {
            console.log('正确答案已记录')
          }).catch(error => {
            console.error('记录正确答案失败:', error)
          })
        } else {
          // 错误显示解析
          this.analysisShow = true

          this.$message({
            message: '很遗憾，做错了呢，请参考答案解析！',
            type: 'error'
          })
          
          // 将错题加入错题本，使用clear=false表示答案错误
          fillResult({
            repoId: this.examId,
            sequence: this.quId,
            clear: false
          }).then(response => {
            console.log('错题已加入错题本')
          }).catch(error => {
            console.error('加入错题本失败:', error)
          })
        }
      }
    }

  }
}
</script>

<style scoped>

  .qu-content div{
    line-height: 30px;
  }

  .qu-analysis p{
    color: #555; font-size: 14px
  }
  .qu-analysis-line{
    margin-top: 20px; border-bottom: #eee 1px solid
  }

  .el-checkbox-group label,.el-radio-group label{
    width: 100%;
  }

  .ai-analyze-btn{
    background: linear-gradient(135deg, #409EFF 0%, #2F74FF 50%, #1F59FF 100%);
    border: none;
    border-radius: 18px;
    padding: 8px 14px;
    box-shadow: 0 4px 12px rgba(64,158,255,0.35);
    display: inline-flex;
    align-items: center;
  }
  .ai-analyze-btn:hover{
    filter: brightness(1.05);
    box-shadow: 0 6px 16px rgba(64,158,255,0.45);
  }

</style>